<template>
  <div class="mapContain">
      <div class="tabContent">
          <div class="tab">2D</div>
      </div>
      <div class="top">
          <div class="up">底图上传</div>
          <el-upload
            :class="{uoloadSty:showUpload,disUoloadSty:noshowUpload}"
            :action="upload"
            list-type="picture-card"
            :on-change="changeImage"
            :on-remove="handleRemove"
            :on-success="handleAvatarSuccess"
            :file-list="imgList"
            :limit="1">
            <i class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
      </div>
      <div ref="map" class="map"></div>
      <div class="button-wrapper w-full flex justify-center mb-2">
                  <vs-button
                    color="primary"
                    type="filled"
                    icon-pack="feather"
                    icon="icon-check"
                    size="small"
                    class="bg-primary-gradient"
                    @click="save"
                  >保存</vs-button>
                </div>
      <vx-popup
        title="配置截面"
        width="680px"
        @close="cancelFormSubmit"
        :active.sync="add"
        @confirmPopup="submit"
        @cancelPopup="cancelFormSubmit"
      >
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
          <el-form-item label="截面配置" prop="name">
            <el-select v-model="ruleForm.name" placeholder="请选择截面">
              <el-option v-for="(item, index) in list" :key="index" :label="item.sectionName" :value="`${item.sectionName}@${item.id}`" :disabled="item.disabled"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
    </vx-popup>
  </div>
</template>

<script>
import mapboxgl from "mapbox-gl";
import base from "../../../api/base";
export default {
  name: "AddSite",
  props: {
    ownId: {
      type: String
    },
    facadeId: {
      type: String
    }
  },
  data() {
    return {
      upload: base.UPLOADURL,
      download: base.DOWNLOADURL,
      showUpload: true,
      noshowUpload: false,
      siteId: '',
      add: false,
      ruleForm: {
        name: ''
      },
      rules:{},
      list: [],
      imageUrl:require('../../../assets/mapbox/bg.png'),
      imgList: [],
      path: '',
      id:'',
      e: {},
      arr: [],
      pointList: [],
      repeatList: [],
      first: false,
      geojson: {
        type: "FeatureCollection",
        features: []
      },
      zoom: 16.9, // 缩放级别
      proportion: '', //图片比例
      yPoint: 0.0010127542875721929,
      coordinates: [
        [-76.54335737228394, 39.18579907229748],
        [-76.52803659439087, 39.1838364847587],
        [-76.5295386314392, 39.17683392507606],
        [-76.54520273208618, 39.17876344106642]
      ]
    }
  },
  mounted() {
    this.getMap()
  },
  watch: {
    'ownId': {
      handler(val, old) {
        this.getList()
      },
      immediate: true
    }
  },
  methods: {
    handleAvatarSuccess(res, file) {
      console.log(res.data)
      this.imageUrl = URL.createObjectURL(file.raw);
      this.path = res.data.successFiles[0].filePath
      this.id = res.data.successFiles[0].id
      var img = new Image();
      img.src = this.download + this.path
      img.onload = ()=>{
        this.proportion = (Number(img.width)/Number(img.height)).toFixed(2)
        let xPoint = this.proportion * this.yPoint
        this.coordinates = [
          [-xPoint, this.yPoint],
          [xPoint, this.yPoint],
          [xPoint, -this.yPoint],
          [-xPoint, -this.yPoint]
        ]
      }
      setTimeout( () => {
          var map = this.map.getSource('overlay')
          map.updateImage({url:this.imageUrl})
          map.setCoordinates(this.coordinates)
      },1000)
    },
    changeImage(file, fileList){
      this.noshowUpload = fileList.length >= 1;
    },
    handleRemove(file, fileList) {
      this.imageUrl = ''
      this.path = ""
      this.id = ''
      this.pointList = []
      this.first = true
      var map = this.map.getSource('overlay')
      map.updateImage({url:require('../../../assets/mapbox/bg.png')})
      this.arr.map(v => {
        v.remove()
      })
      this.list.map(v => {
        v.disabled = false
      })
      this.noshowUpload = false
    },
    submit() {
      let test = this.ruleForm.name.substring(0,this.ruleForm.name.indexOf('@'))
      let code = this.ruleForm.name.substring(this.ruleForm.name.indexOf('@')+1)
      if (test != null && test != "") {
        this.list.map(v => {
          if(v.name === test) {
            v.disabled = true
          }
        })
        let data = {
          type: "Feature",
          properties: {
            message: test,
            id: code,
            iconSize: [80, 80]
          },
          geometry: {
            type: "Point",
            coordinates: [this.e.lngLat.lng, this.e.lngLat.lat]
          }
        }
        //调用创建dom 生成marker 方法
        this.initMarker(data);
        this.pointList.push(data)
      }
      this.add = false
      this.ruleForm.name = ''
    },
    cancelFormSubmit() {
      this.add = false
      this.ruleForm.name = ''
    },
    //初始化列表数据
    getList() {
      const params = {
        ownId: this.ownId
      };
      if(!this.ownId){
        return false
      }
      this.$api.bridge.queryBridgeCrossSections(params).then(res => {
        if(res&&res.data&&res.data.data && res.data.data.length > 0){
          res.data.data.map(v => {
            v.disabled = false
          })
        }

         this.list =res && res.data.data ? res.data.data[0] : []
        setTimeout(() => {
          this.get()
        }, 1000);

      })
    },
     // 初始化地图
    initMap() {
      mapboxgl.accessToken =
        // "pk.eyJ1IjoieHVzaGFucGVpIiwiYSI6ImNqenl5M2t0aTA0dzczY3AzdXJoajB6emcifQ.Gpduip9bhda1q8BX2Xc2UQ";
        "pk.eyJ1IjoiYW9mZW5nMjAwMCIsImEiOiJja252a3Q4cWkwazU3MnZwZDZ2MDN0MDg5In0.7HHfJfVC4Mht7IeL5yO4kQ";
      var mapStyle = {
        version: 8,
        name: "Dark",
        sources: {
          mapbox: {
            type: "vector",
            url: "mapbox://mapbox.mapbox-streets-v8"
          },
          overlay: {
            type: "image",
            url: this.imageUrl,
            coordinates: this.coordinates
          }
        },
        layers: [
          {
            id: "overlay",
            source: "overlay",
            type: "raster"
          }
        ]
      }
      this.map = new mapboxgl.Map({
        style: mapStyle,
        center: [0, 0], //地图中⼼经纬度
        zoom: this.zoom, //缩放级别
        // minZoom: 15.5,
        maxZoom: 24,
        pitch: 0,
        // bearing: -17.6,
        container: this.$refs.map,
        zoomAdjust: null,
        antialias: true,
        dragRotate: false,
        touchZoomRotate: false
      });
      // if(this.geojson.features.length > 0) {
        // this.geojson.features.forEach(item => {
          //调用创建dom 生成marker 方法
          // this.initMarker(item);
        // });
      // }
    },
     // 创建dom 元素生成 marker

    initMarker(data) {
      // 创建一个点
      var el = document.createElement("div");
      el.className = "marker";
      el.style.backgroundSize = "36px";
      el.style.backgroundRepeat = "no-repeat";
      el.style.backgroundPosition = "center";
      el.style.backgroundImage = "url(point.png)";
      el.style.cursor = "grab";
      el.addEventListener("click", e => {
        console.log(data);
        e.stopPropagation();
        console.log("点击的玩意", data.properties);
        // window.alert(data.properties.message);
      });
      // 创建文字信息
      var textEl = document.createElement("div");
      textEl.className = "marker";
      textEl.textContent = data.properties.message;
      textEl.style.backgroundColor = "rgba(51,51,51,.7)";
      textEl.style.height = "20px";
      textEl.style.borderRadius = "3px";
      textEl.style.paddingLeft = "5px";
      textEl.style.paddingRight = "5px";
      textEl.style.marginTop = "50px"
      textEl.style.display = "inline-block";
      textEl.style.color = "#3ED385";
      el.appendChild(textEl);
      textEl.addEventListener("click", e => {
        console.log(data);
        e.stopPropagation();
        // window.alert(data.properties.message);
      });

      // 创建删除
      var del = document.createElement("span");
      del.className = "del";
      del.textContent = `×`;
      del.style.marginLeft = "5px";
      del.style.color = "#000";
      del.style.fontSize = "15px";
      del.style.display = "inline-block";
      del.style.backgroundColor = "red";
      del.style.width = "14px";
      del.style.height = "14px";
      del.style.borderRadius = "50%";
      del.style.textAlign = "center";
      del.style.lineHeight = "13px";
      del.style.cursor = "pointer";
      textEl.appendChild(del);
      // add marker to map
      var marker = new mapboxgl.Marker(el)
        .setLngLat(data.geometry.coordinates)
        .setDraggable(true)
        .addTo(this.map);
      this.arr.push(marker)
      del.addEventListener("click", e => {
        console.log("删除的玩意", marker);
        // alert("删除的玩意"+ marker.data.message)
        e.stopPropagation();
        marker.remove();
        this.pointList.map((v,index) => {
          if(v.properties.id === marker.data.id) {
            this.pointList.splice(index,1)
          }
        })
        this.list.map(v => {
          if(v.name === marker.data.message) {
            v.disabled = false
          }
        })
      });

      marker.data = data.properties;
      marker.on("dragend", e => {
        console.log("移动的玩意", marker);
        // alert("移动的玩意"+ marker.data.message)
        //鼠标移动开始
        console.log("鼠标移动结束", marker.getLngLat(), marker.data);
        this.pointList.map((v,index) => {
          if(v.properties.id === marker.data.id) {
            v.geometry.coordinates = [marker.getLngLat().lng, marker.getLngLat().lat]
          }
        })
      });
    },
    // 点击地图的方法
    clickMap() {
      this.map.on("click", e => {
        if(this.imageUrl !== '' ) {
        // if(this.imageUrl !== '' && this.isShow) {
        // 点击前可以初始化弹出框
        this.add = true
        this.e = e
        } else {
          this.add = false
        }
      });
    },
    //提交
    save() {
      let params = {
        ownId: this.ownId,
        facadeId: this.facadeId,
        twoDimension:{
          path: this.path,
          id:this.id
        },
        viewList: this.pointList || [],
        coordinates: this.coordinates
      }
      let arr = []
      if(this.pointList.length > 0) {
          this.pointList.map(v => {
              let obj = {}
              obj.id = v.properties.id
              obj.lng = v.geometry.coordinates[0]
              obj.lat = v.geometry.coordinates[1]
              arr.push(obj)
          })
          this.repeatList = arr
      }
      if(this.path === '') {
        this.$vs.notify({
          text: "请上传图片",
          color: 'danger'
        })
      } else {
        if(this.siteId !== '') {
          this.$api.bridge.updateBridgeFacadeById({...params,id:this.siteId}).then(res => {
            if(res.data.success){
               this.$vs.notify({
              text: "截面配置成功",
              color: "success"
            })
            } else{
              this.$vs.notify({
              text: '截面配置失败',
              color: 'danger'
            })
            }
          })
        } else {
        this.$api.bridge.addBridgeFacade(params).then(res => {
          if(res.data.success) {
            this.$vs.notify({
              text: "截面配置成功",
              color: "success"
            })
          } else {
            this.$vs.notify({
              text: '截面配置失败',
              color: 'danger'
            })
          }
        })
        }
        this.$api.bridge.batchUpdateBridgeCrossSection(this.repeatList).then(res => {
          if(res.data.success) {

          }
        })
      }

    },
    //查询
    get() {
      let params = {
        ownId: this.ownId,
        facadeId: this.facadeId
      }
      this.$api.bridge.queryAllBridgeFacade(params).then(res => {
        if(res.data.success && res.data.data &&res.data.data[0].length > 0) {
          let result = res.data.data[0]
          let data = result[0]
          this.first = true
          this.path = data.twoDimension.path
          this.imageUrl = this.download + data.twoDimension.path
          let obj = {
            name:'111.png',
            url: this.imageUrl
          }
          this.imgList = [obj]
          this.noshowUpload = true
          this.pointList = data.viewList || [];
          this.siteId = data.id
          this.coordinates = data.coordinates
          var map = this.map.getSource('overlay')
          map.updateImage({url:this.imageUrl})
          map.setCoordinates(this.coordinates)
          this.arr.map(v => {
            v.remove()
          })
          if(this.pointList.length > 0) {
            this.pointList.forEach(item => {
              //调用创建dom 生成marker 方法
              this.initMarker(item);
            });
          }
          if(data.viewList.length > 0){
            if(this.list.length > 0) {
              data.viewList.map(v => {
                this.list.map(v1 => {
                  if(v.properties.id === v1.id) {
                    v1.disabled = true
                  }
                })
              })
            }
          }
        }else{
          this.first = true
          this.path = ''
          this.imageUrl = require('../../../assets/mapbox/bg.png');
          this.imgList = []
          this.pointList = []
          this.noshowUpload = false
          var map = this.map.getSource('overlay')
          map.updateImage({url:this.imageUrl})
          map.setCoordinates([
        [-76.54335737228394, 39.18579907229748],
        [-76.52803659439087, 39.1838364847587],
        [-76.5295386314392, 39.17683392507606],
        [-76.54520273208618, 39.17876344106642]
      ])
          this.arr.map(v => {
            v.remove()
          })
        }
      })
    },
    getMap(){
      this.initMap()
      this.clickMap()
    }
  }

}
</script>

<style scoped lang="scss">
.top{
  /* border-bottom:1px solid #eee; */
  display: flex;
  align-items: center;
  height:100px;
  position: fixed;
  z-index: 100 !important;
}
.up{
  margin-right:10px;
}
/deep/.uoloadSty .el-upload--picture-card {
  width:60px;
  height: 60px;
  line-height: 60px;
  text-align: center;
  font-size: 28px;
}
/deep/.disUoloadSty .el-upload--picture-card{
  display:none;   /* 上传按钮隐藏 */
}
/deep/.el-upload-list--picture-card .el-upload-list__item {
  width:60px;
  height: 60px;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 60px;
  height: 60px;
  line-height: 60px;
  text-align: center;
}

.mapContain{
  width:100%
}

.map{
  width:100%;
  margin:20px 0;
  height:400px;
}
.tabContent {
    width:100%;
    height:64px;
    border-bottom: 1px solid #E3E8F2;
}
.tab {
    width:70px;
    height:34px;
    background:$mainColor;
    border-radius:17px;
    text-align: center;
    line-height: 34px;
    color: #fff;
    font-size: 14px;
}
</style>
